package routers

import (
	"EnjoyWorking/utils"
	"EnjoyWorking/web/controller"
	"EnjoyWorking/web/middleware"
	"github.com/iris-contrib/middleware/cors"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
	rcover "github.com/kataras/iris/v12/middleware/recover"
)

// 路由方法
// 进行路由分组
func Routers(app *iris.Application){
	party := preSettring(app)

	controller.NewAdminUserController(app, party)
	controller.NewJobController(app, party)
	controller.NewDepartmentController(app, party)
	controller.NewProjectController(app, party)
	controller.NewWprController(app, party)
	controller.NewWprItemController(app, party)

	controller.NewInterfaceDetailController(app, party)
}

func preSettring(app *iris.Application) (party iris.Party) {
	//app.Logger().SetLevel(common.G_AppConfig.LogLevel)
	logger, _ := utils.NewRequestLogger()
	//defer close()
	app.Use(
		rcover.New(), // 恢复
		logger,       // 记录请求
		//middleware.ServeHTTP
	)
	// 定义错误处理
	app.OnErrorCode(iris.StatusNotFound, logger, func(context *context.Context) {
		utils.Error(context, iris.StatusNotFound, utils.CODE_NOTFOUNT)
	})

	app.OnErrorCode(iris.StatusInternalServerError, logger, func(context *context.Context) {
		utils.Error(context, iris.StatusInternalServerError, utils.CODE_FAILUR)
	})
	//app.OnErrorCode(iris.StatusForbidden, customLogger, func(ctx iris.Context) {
	//	ctx.JSON(utils.Error(iris.StatusForbidden, "权限不足", nil))
	//})
	//捕获所有http错误:
	//app.OnAnyErrorCode(customLogger, func(ctx iris.Context) {
	//	//这应该被添加到日志中，因为`logger.Config＃MessageContextKey`
	//	ctx.Values().Set("logger_message", "a dynamic message passed to the logs")
	//	ctx.JSON(utils.Error(500, "服务器内部错误", nil))
	//})

	// 设置跨域
	crs := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowedHeaders: []string{"*"},
		//Debug:            true,
	})
	party = app.Party("/api", crs).AllowMethods(iris.MethodOptions)
	party.Use(middleware.ServeHTTP)
	return party
}